<template>
  <van-notice-bar
      left-icon="volume-o"
      text="缘来是你，遇见专属心动    心动邂逅，开启缘分之门"
      color="#1989fa"
      background="#ecf9ff"
      scrollable
  />
  <van-cell center title="心动模式" style="margin-bottom: 4px">
    <template #icon>
      <van-icon name="question-o" style="margin-right: 4px" size="16px" @click="doAlertUseDesc"/>
    </template>
    <template #right-icon>
      <van-switch v-model="isRunMatches"/>
    </template>
  </van-cell>
  <user-list-card :user-list=userList :loading="loading"></user-list-card>
  <van-empty description="内容为空" v-if="userList ==  null|| !userList"></van-empty>
  <van-loading v-if="loading" style="margin: 10px auto; align-items: center" />
</template>

<script setup lang="ts">
import {onBeforeUnmount, onMounted, ref, watch} from "vue";
import {showSuccessToast, showFailToast, showDialog} from 'vant';
import 'vant/lib/index.css';
import UserListCard from "../components/UserListCard.vue";
import {getUserMatches, getUserRecommend} from "../api/User.js";
import type {UserType} from "../models/User";

const isRunMatches = ref<boolean>(false);

// 获取用户匹配列表
const userList = ref<UserType[]>([]);
const loading = ref(false);

// 是否还有更多数据
const hasMore = ref(true);
// 当前页码
const pageIndex = ref<number>(1);
// 每页显示8条
const pageSize = 8;

// 存储两种模式下的用户列表
const recommendUserList = ref<UserType[]>([]); // 推荐模式数据
const matchesUserList = ref<UserType[]>([]);   // 心动模式数据

const loadIndex = async () => {
  let userListResult;
  loading.value = true;

  if (!isRunMatches.value) {
    /**
     * 普通模式
     */
    userListResult = await getUserRecommend(pageIndex.value, pageSize)
        .then(function (response) {
          // 处理成功情况
          // 后端运用了mybatisPlus的分页功能，导致参数传递错误，所以返回的参数为 records
          return response?.data?.records;
        })
        .catch(function (error) {
          // 处理错误情况
          console.log("/user/recommend error" + error);
          showFailToast('主页加载失败');
          return [];
        });

    // 解析标签
    if (userListResult.length > 0) {
      userListResult.forEach((user: UserType) => {
        user.tags = JSON.parse(user.tags);
      });

      // 累加数据
      recommendUserList.value = [...recommendUserList.value, ...userListResult];
      userList.value = recommendUserList.value;

      if (userListResult.length < pageSize) {
        hasMore.value = false;
      }
    } else {
      hasMore.value = false;
    }
  } else {
    /**
     * 点击开关时开启心动模式
     */
    if (matchesUserList.value.length === 0) {
      const num = 10;
      userListResult = await getUserMatches(num)
          .then(function (response) {
            // 处理成功情况
            console.log("/user/matches success" + response);
            showSuccessToast("心动用户挑选成功")
            return response?.data;
          })
          .catch(function (error) {
            // 处理错误情况
            console.log("/user/matches error" + error);
            showFailToast('加载失败');
            return [];
          });

      // 解析标签
      if (userListResult.length > 0) {
        userListResult.forEach((user: UserType) => {
          user.tags = JSON.parse(user.tags);
        });
        // 添加用户列表数据
        matchesUserList.value = userListResult;
        userList.value = matchesUserList.value;
      }
    } else {
      userList.value = matchesUserList.value;
    }
  }

  loading.value = false;
}


// 防抖函数：500ms内只执行一次
const debounce = (fn: () => void, delay = 500) => {
  let timer: number | null = null;
  return () => {
    if (timer) clearTimeout(timer);
    timer = window.setTimeout(fn, delay);
  };
};
// 请求锁
const isLocked = ref<boolean>(false);

// 监听滚动事件
// 用防抖包装滚动事件处理函数
const handleScroll = debounce(() => {
  if (isLocked.value) return; // 锁住时不执行

  const scrollTop = window.scrollY || document.documentElement.scrollTop;
  const windowHeight = window.innerHeight;
  const bodyHeight = document.body.scrollHeight;

  // 滚动到底部附近（50px内），且可以加载更多
  if (bodyHeight - scrollTop - windowHeight < 50 && !loading.value && hasMore.value) {
    isLocked.value = true;
    pageIndex.value += 1;
    loadIndex().finally(() => {
      setTimeout(() => {
        isLocked.value = false;
      }, 500)
    });
  }
}, 300);

// 挂载时加载
onMounted(() => {
  window.addEventListener('scroll', handleScroll);
  loadIndex();
})

// 切换模式时更新显示内容，不主动加载
watch(() => isRunMatches.value, (newVal) => {
  if (!newVal) {
    // 推荐模式：恢复历史数据
    userList.value = recommendUserList.value;
    hasMore.value = recommendUserList.value.length >= pageSize;
  } else {
    // 心动模式：恢复已有数据或等待首次加载
    userList.value = matchesUserList.value;
  }
});

// 页面卸载时清除状态
onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll);
  recommendUserList.value = [];
  matchesUserList.value = [];
})

// 心动模式使用说明弹窗提示
const doAlertUseDesc = () => {
  showDialog({
    title: '心动模式 ?',
    message: '心动模式可以根据您的标签帮您匹配最相似的用户，便于您快速交友',
    width: 280,
  }).then(() => {
    // on close
  });
}

</script>

<style scoped>
/* 调整 z-index 确保不被遮挡，同时设置最小显示区域 */
.van-toast {
  z-index: 9999 !important;
  min-width: 120px; /* 保证文字能显示 */
  visibility: visible !important;
}
</style>